import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 当前位置
  String currentLocation = "";
  // 周边社区
  List<dynamic> aroundList = [];
  @override
  void initState() {
    super.initState();
    _getPermission();
  }

// 动态请求位置
  void _getPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 获取位置
      // PromptAction.showToast('获取位置成功');
      _getLocation();
    } else {
      // 拒绝
      PromptAction.showToast('获取位置失败');
    }
  }

  // 获取用户信息
  /* 
  web端获取经纬度（位置信息）有bug
  有时候可能获取不到 没关系 后续会虚拟出经纬度
  核心逻辑：基于经纬度 获取位置和周边社区（核心） */
  void _getLocation() async {
    Position position = await Geolocator.getCurrentPosition();
    // PromptAction.showToast('经度: ${position.longitude}');
    // PromptAction.showToast('纬度: ${position.latitude}');
    // 逆地址解析
    _getAddress(position.longitude, position.latitude);
    // 获取周边社区
    _getAround(position.longitude, position.latitude);
  }

  // 逆地址解析：基于经纬度 -> 地址
  // 3baba5883a9154c485e23c49b3fb7118
  _getAddress(double longitude, double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(GlobalVariable.GAODE_URL + HTTP_PATH.GAODE_REGEO,
        queryParameters: {
          'key': GlobalVariable.GAODE_KEY,
          'location': '$longitude,$latitude',
        });
    if (res.data['status'] == '1') {
      setState(() {
        currentLocation = res.data['regeocode']['formatted_address'];
      });
    }
    // print(res);
  }

  // 获取周边社区 基于经纬度
  _getAround(double longitude, double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(GlobalVariable.GAODE_URL + HTTP_PATH.GAODE_AROUND,
        queryParameters: {
          'key': GlobalVariable.GAODE_KEY,
          'location': '$longitude,$latitude',
          'keywords': '附近社区',
          'offset': 10,
        });
    if (res.data['status'] == '1') {
      setState(() {
        aroundList = res.data['pois'];
      });
    }
  }

  // 社区列表
  List<Widget> getAroundList() {
    return aroundList.map((item) {
      return Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10),
        child: Row(
          children: [
            Expanded(child: Text(item['name'])),
            const Row(
              children: [
                Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
              ],
            )
          ],
        ),
      );
    }).toList();
  }

  // 重新定位 -> 北京天安门
  resetLocation() {
    // 逆地址解析
    _getAddress(121.440641, 31.193908);
    // 获取周边社区
    _getAround(116.397455, 39.909187);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(currentLocation)),
                GestureDetector(
                  onTap: () {
                    resetLocation();
                  },
                  child: const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getAroundList(),
          )
        ],
      ),
    );
  }
}
